import qs from 'qs';
export default {
  stringify: (origin = {}) => {
    var newObj = {};
    Object.keys(origin).forEach(function (key) {
      if (origin[key] && origin[key] instanceof Array) {
        newObj[key] = origin[key].join(',');
      } else {
        newObj[key] = origin[key];
      }
    });
    return qs.stringify(newObj);
  },
	encodeJSON: function (obj) {
		return encodeURIComponent(JSON.stringify(obj))
	},
	decodeJSON: (str) => {
		return JSON.parse(decodeURIComponent(str));
	},
  getFmtDate: function (date, fmt = 'yyyy-MM-dd') {
  if (!date) { return ''; }
  if (date instanceof Array) {
    return date.map(n => getFmtDate(new Date(n))).join(',');
  }
  var o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
    "q+": Math.floor((date.getMonth() + 3) / 3),
    "S": date.getMilliseconds()
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
},
  getQueryString: function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
  },
  toggleAttr: function (arr, index, attrName = 'active') {
    arr.forEach(element => {
        element[attrName] = false;
    });
    if (index instanceof Function) {
      index = arr.findIndex(index);
    }
    arr[index] && (arr[index][attrName] = true);
  },
  pickValueFromArray: function (array, foo, fieldName = 'value', defaultValue = '') {
    var item = array.find(foo);
    return item ? item[fieldName] : defaultValue;
  },
  cloneObject: function (obj) {
    return JSON.parse(JSON.stringify(obj));
  },
  arrayListToTree(source) {
    for (let i = 0; i < source.length; i++) {
      let arrTemp = []
      for (let j = 0; j < source.length; j++) {
        if (source[i].id == source[j].pId) {
          source[i].children = arrTemp
          arrTemp.push(source[j])
        }
      }
    }
    const result = []
    for (let i = 0; i < source.length; i++) {
      if (source[i].pId == 'null' || !source[i].pId) {
        result.push(source[i])
      }
    }
    return result;
  },
  getRandomRgbColor: function () {
    return new Array(3).fill(255).map((o) => {
      return o * Math.random();
    });
  },
  uuid: function () {
   return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) + (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) + (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  },
  filterUtil: (list, name, type = 'type') => {
    return list.filter((o) => o[type] == name);
  },
  
  splitFmt: function (v, p = '') {
    return v.split(p).map(n => '<p>' + n + '</p>').join('');
  },
  isNewEvent (date) {
    if (date) {
      return Date.now() - new Date(date) < 5 * 60000;
    }
    return false;
  },
	mergeVariables: function (arr, vars, name, force) {
		if (!arr || !name) {
			return;
		}
		var length = vars.length;
		arr.forEach((n, i) => {
			if (n[name] && !force) {
				return;
			} else {
				n[name] = vars[i % length];
			}
		});
	},
  isJSON(target) {
    return typeof target == "object" && target.constructor == Object;
  },
  mergeJSON (minor, main = {}) {
    var main = this.cloneObject(main);
    for (var key in minor) {
      if (main[key] === undefined) {  // 不冲突的，直接赋值
        main[key] = minor[key];
        continue;
      }
  
      // 冲突了，如果是Object，看看有么有不冲突的属性
      // 不是Object 则以main为主，忽略即可。故不需要else
      if (this.isJSON(minor[key])) {
        // arguments.callee 递归调用，并且与函数名解耦
        main[key] = this.mergeJSON(minor[key], main[key]);
      }
    }
    return main;
  }
};
